import {message} from 'ant-design-vue';
import axios, {type AxiosRequestConfig} from 'axios';
import type {IBaseRequest, IPageRequest} from '@/types/request';

export const BASE_URL = 'https://backend-course.xdproject.top';
const request = axios.create({baseURL: `${BASE_URL}/api/admin/v1`});

// 请求拦截器
request.interceptors.request.use((config) => {
    const {token} = $(useAuth());
    if (token) {
        config.headers.Authorization = token;
    }
    return config;
});

// 响应拦截器
request.interceptors.response.use((response) => {
    const data = response.data;

    if (data.code !== 0) {
        message.error(data.msg);
    }
    return response;
});

export default async function <T = any, P extends boolean = false>(
    url: string,
    options?: AxiosRequestConfig
) {
    return (
        await request({
            url,
            ...options,
        })
    ).data as P extends true ? IPageRequest<T> : IBaseRequest<T>;
}

